// components/article/index.js
const {
  checkLogin
} = require('../../utils/util')
const {
  collectCourse
} = require('../../api/api')
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    list: {
      type: Array,
      value: []
    },
    mode: {
      type: String,
      value: 'simple'
    },
    setting: {
      type: Object,
      value: {}
    },
    maxLine:{
      type:Number,
      value:1
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    async goto(e) {
      const {
        url,
        value,
        navigate,
        auth,
        index,
        cid,
        link
      } = e.currentTarget.dataset
      if(link){
        wx.showLoading({
            title: '正在加载文件...',
            mask: true
          })
          wx.downloadFile({
            url: link,
            success: function (res) {
              wx.hideLoading()
              const tempFilePath = res.tempFilePath;
              wx.openDocument({
                filePath: tempFilePath,
                success: function (res) {
                  console.log('打开文档成功')
                },
              });
      
            },
            fail() {
              wx.hideLoading()
            }
          });
        return
      }
      if (auth) {
        if (value.json) {
           const jsons= JSON.parse(value.json)
           if(jsons.vipUrl){
              const {vipType}= await getApp().fetchUserInfo()
              if(vipType && jsons.tab){
                wx.switchTab({
                  url: jsons.vipUrl,
                })
                return
              }
              if(vipType && !jsons.tab){
                wx.navigateTo({
                  url: jsons.vipUrl,
                })
                return
              }
              
           }
        }
        // checkLogin().then((res) => {
          if (cid) {
            this.triggerEvent('update', value)
          } else {
            wx.navigateTo({
              url: url + '?params=' + encodeURIComponent(JSON.stringify(value)),
            })
          }
        // }).catch((e) => {
        //   this.triggerEvent('login')
        // })
      } else {
        wx.navigateTo({
          url: url + '?params=' + encodeURIComponent(JSON.stringify(value)),
        })
      }


    },
    // 院校收藏
    async collect(e) {
      const {
        id,
        index,
        pindex,
        iscollect
      } = e.currentTarget.dataset
      const {
        list
      } = this.data
      list[pindex][index].isCollection = !iscollect
      const result = await collectCourse(id)
      wx.showToast({
        title: result.message,
        icon: 'none'
      })
      const params = {
        list: this.data.list,
        pindex,
        index
      }
      this.triggerEvent("collect", params);
    }
  }
})
